package com.takepoints.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.takepoints.android.bo.Promotion;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.ImageUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TPDeals extends BaseActivity {
	
	private ListView lstPromotions = null;
	private PromoListAdapter promoAdapter = null;
	private TextView txtHeader = null;
	private Button btnLoadMore = null;
	private RelativeLayout loadingPanel = null;
	
	//private PromotionsAdapter promoDbApt = null;
	//private SiteLocationsAdapter siteLocDbApt = null;
	
	private int nextPage = 1;
	private boolean isFromOnCreate = false;
	
	private Double myLatitude = 0.00d;
	private Double myLongitude = 0.00d;
	private LocationManager locMgr = null;
	private GeoUpdateListener locListener = null;
	private Criteria criteria = null;
	
	private final String IMG_URL = "https://www.takepoints.com/public/uploads/tmobile/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.promotions);
        
        ImageView imgLogo = (ImageView)findViewById(R.id.imgLogo);
        imgLogo.setImageResource(R.drawable.header_deal);
        
        txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText(R.string.title_card);
        manageMenu(0);

        locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		locListener = new GeoUpdateListener();
		
		btnLoadMore = (Button)findViewById(R.id.btnLoadMore);
        btnLoadMore.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 new FetchCards().execute(String.valueOf(nextPage));
			 }
        });
        //promoDbApt = new PromotionsAdapter(this);
        //siteLocDbApt = new SiteLocationsAdapter(this);
        
        loadingPanel = (RelativeLayout)findViewById(R.id.loadingPanel);
        
        ImageView imgRefresh = (ImageView)findViewById(R.id.imgRefresh);
        imgRefresh.setVisibility(View.GONE);
        
        lstPromotions = (ListView)findViewById(R.id.lstPromotions);
        lstPromotions.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        promoAdapter = new PromoListAdapter(new ArrayList<Promotion>());
        lstPromotions.setAdapter(promoAdapter);
        
        isFromOnCreate = true;
	}
	
	@Override
    protected void onResume(){
    	super.onResume();
		if(!locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			if(isFromOnCreate){
				isFromOnCreate = false;
				openGpsConfirm();
			} else{
				if( promoAdapter.getCount() < 1 )
					takeMyLocation();
			}
		} else{
			if( promoAdapter.getCount() < 1 )
				takeMyLocation();
		}
	}
	
	private void takeMyLocation(){
	        String bestProvider = locMgr.getBestProvider(criteria, true);
	        if(locMgr.isProviderEnabled( bestProvider )){
		            locMgr.requestLocationUpdates( bestProvider, 0, 0, locListener );
		            
			        Location loc = locMgr.getLastKnownLocation( bestProvider );
			        if(loc != null){
					        myLatitude = loc.getLatitude();
					    	myLongitude = loc.getLongitude();
					    	
					    	Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
					        try{
					        	List<Address> addresses = geoCoder.getFromLocation(myLatitude, myLongitude, 1);
					        	if(addresses.size() > 0){
					        		int size = addresses.get(0).getMaxAddressLineIndex();
					        		if(size > 0){
					        			String myAddr = "";
					        			for(int i=0; i<size; i++){
					        				if(i == 0){
							        			myAddr += addresses.get(0).getAddressLine(0);
					        				} else if(i == 1){
							        			myAddr = myAddr + ", " + addresses.get(0).getAddressLine(1);
					        				}
					        			}
					        			txtHeader.setText(myAddr);
					        		}
					        	}
					        } catch(Exception e){ }
					        
					        new FetchCards().execute("1");
			        }
	        }
	}
	
	@Override
    protected void onPause(){
    	super.onPause();
        String bestProvider = locMgr.getBestProvider(criteria, true);
    	if(locMgr.isProviderEnabled( bestProvider )){
        	locMgr.removeUpdates( locListener );
        }
	}
	
	@Override
    protected void onDestroy(){
    	super.onDestroy();
        String bestProvider = locMgr.getBestProvider(criteria, true);
        if(locMgr.isProviderEnabled( bestProvider )){
        	locMgr.removeUpdates( locListener );
        }
    }
	
	private class PromoListAdapter extends BaseAdapter {
		private List<Promotion> promotions;
		private LayoutInflater mInflater;

		public PromoListAdapter(List<Promotion> promotions){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.promotions = promotions;
		}
		
		public void addTop(Promotion promotion){
			promotions.add(0, promotion);
			notifyDataSetChanged();
		}
		public void add(Promotion promotion){
			promotions.add(promotion);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			promotions.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			final View rowView = (convertView!=null)?convertView:mInflater.inflate(R.layout.itemrow, null);
			final Promotion promotion = promotions.get(position);
			if(promotion != null){
				//final TableRow tblCard = (TableRow)convertView.findViewById(R.id.tblCard);
				ImageView imgCard = (ImageView)rowView.findViewById(R.id.imgCard);
				if(imgCard != null){
					Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + promotion.getPicture());
					if(bitmap != null){
						//imgCard.setImageBitmap(bitmap);
						imgCard.setImageBitmap(ImageUtil.getRoundedBitmap(bitmap, 5, Color.GRAY));
					} else{
						imgCard.setTag(IMG_URL + promotion.getPicture());
						new DownloadImageTask().execute(imgCard);
					}
				}
				
				TextView txtPoints = (TextView)rowView.findViewById(R.id.txtPoints);
				txtPoints.setText(promotion.getOfferPts());
				
				//TextView txtFar = (TextView)rowView.findViewById(R.id.txtFar);
				//txtFar.setText(LocationUtil.displayKmText(promotion.getDistance()));
				
				LinearLayout lnrDetail = (LinearLayout)rowView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					TextView txtTitle = new TextView(lnrDetail.getContext());
					//txtTitle.setText(promotion.getSiteName());	// promotion.getCustName()
					txtTitle.setText(promotion.getCustomerName() + " (" + promotion.getSiteName() + ")");
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#78a023"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txt1 = new TextView(lnrDetail.getContext());
					txt1.setText(promotion.getTitleName());
					txt1.setTextSize(11);
					txt1.setTextColor(Color.parseColor("#404a4a"));
        	        txt1.setHeight(LayoutParams.WRAP_CONTENT);
					txt1.setPadding(9, 1, 1, 1);
					txt1.setSingleLine(false);
					lnrDetail.addView(txt1);
				}
				
				rowView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent promoDetailInt = new Intent(view.getContext(), TPPromoDetail.class);
						 promoDetailInt.putExtra("promoId", promotion.getPromotionId());
						 promoDetailInt.putExtra("promoTypeId", promotion.getPromoTypeId());
						 promoDetailInt.putExtra("picture", promotion.getPicture());
						 promoDetailInt.putExtra("custSiteName", promotion.getCustomerName() + " (" + promotion.getSiteName() + ")");
						 startActivityForResult(promoDetailInt, 0);
					 }
				});
				rowView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		rowView.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				});
			}
			return rowView;
		}

		@Override
		public int getCount() {
			return promotions.size();
		}

		@Override
		public Object getItem(int position) {
			return promotions.get(position);
		}

		@Override
		public long getItemId(int position) {
			return promotions.get(position).hashCode();
		}
	}
	
	class FetchCards extends AsyncTask<String, Void, List<Promotion>>{
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            loadingPanel.setVisibility(View.VISIBLE);
        }
        
        @Override
        protected List<Promotion> doInBackground(String... params){
        	int page = Integer.parseInt(params[0]);
        	List<Promotion> promoL = null;
        	/*if(myLatitude > 0.00d && myLongitude > 0.00d){
        		infoL = PublicServices.getNearByPromotions( String.valueOf(myLatitude)
        												  , String.valueOf(myLongitude)
        												  , PublicServices.PROMOTION_TYPE_DEAL
        												  , page);
        	}*/
        	promoL = PublicServices.getPromotionList(PublicServices.PROMOTION_TYPE_DEAL, page);
        	return promoL;
        }
        
        @Override
        protected void onPostExecute(List<Promotion> result){
        	int rows = (result==null)?0:result.size();
        	for(int i=0; i<rows; i++){
        		Promotion pro = result.get(i);
				promoAdapter.add(pro);
        	}
        	
        	if(rows > 0){
        		Promotion info = result.get(0);
	            ++nextPage;
	            if(nextPage > info.getTotalPage()){
	            	btnLoadMore.setVisibility(View.GONE);
	            }
        	} else{
        		btnLoadMore.setVisibility(View.GONE);
        	}
        	loadingPanel.setVisibility(View.GONE);
        }
    }
	
	private void openGpsConfirm(){
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage("GPS ถูกปิดการใช้งานอยู่ !\n\nคุณต้องการเปิด GPS ใช่มั้ย ?");
		alertbox.setPositiveButton("ต้องการ", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	            startActivity(intent);
			}
		});
		alertbox.setNeutralButton("ไม่ต้องการ", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				takeMyLocation();
				dlgInf.dismiss();
			}
		});
		alertbox.show();
	}
	
	public class GeoUpdateListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            myLatitude = location.getLatitude();
        	myLongitude = location.getLongitude();
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
	
}
